//
//  ContentView.swift
//  iosCourse
//
//  Created by 武怡凡 on 2025/5/2.
//

import SwiftUI 
import Combine
import Foundation
import UIKit
import SQLite3
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif


struct ContentView: View {
    @State private var selectedTab = 0
    @State private var selectedCampusIndex = 0
    @State private var selectedCollegeIndex = 0
    
    let campuses = ["浑南校区", "南湖校区"] // 校区列表
    let colleges = ["计算机学院", "外国语学院", "经济管理学院"] // 学院列表
    
    var body: some View {
        TabView(selection: $selectedTab) {
            HomeView()
                .tabItem {
                    Image(systemName: "house")
                    Text("首页")
                }
                .tag(0)
            
            CampusGuideView()
                .tabItem {
                    Image(systemName: "map")
                    Text("指北")
                }
                .tag(1)
            
            ForumView()
                .tabItem {
                    Image(systemName: "bubble.left.and.bubble.right")
                    Text("论坛")
                }
                .tag(2)
            
            ProfileView(id: "123456",
                        avatar: Image(systemName: "person.circle.fill"),
                        myGuide: "我的指北内容",
                        myPosts: "我的帖子内容",
                        contactUs: "联系我们内容",
                        version: "1.0.0")
                .tabItem {
                    Image(systemName: "person")
                    Text("个人主页")
                }
                .tag(3)
        }
        .onAppear {
            initializeDatabase()
        }
    }
    
    func initializeDatabase() {
        SQLManager.shareInstance().createDataBaseTableIfNeeded()
        let insertSQL = "INSERT INTO users (email, password) VALUES ('123@123.com', '123');"
        if SQLManager.shareInstance().execSQL(SQL: insertSQL) {
            print("用户数据插入成功！")
        } else {
            print("用户数据插入失败！")
        }
    }
}

/*################### 主页界面 #####################*/
struct HomeView: View {
    var body: some View {
        VStack {
            Text("首页")
                .font(.title)
                .fontWeight(.bold)
                .multilineTextAlignment(/*@START_MENU_TOKEN@*/.leading/*@END_MENU_TOKEN@*/)
            
            ScrollView {
                VStack(spacing: 20) {
                    // 轮播图
                    ImageCarouselView()
                        .frame(height: 200)
                    
                    // 热点指北
                    ZStack {
                        RoundedRectangle(cornerRadius: 25)
                            .fill(Color.white)
                            .shadow(color: Color.black.opacity(0.1), radius: 5, x: 0, y: 5)
                        
                        HotSpotView()
                    }
            
                    
                    ZStack {
                        RoundedRectangle(cornerRadius: 25)
                            .fill(Color.white)
                            .shadow(color: Color.black.opacity(0.1), radius: 5, x: 0, y: 5)
                        
                        // 热点论坛讨论话题
                        HotForumTotalView()
                    }
                    
                }
            .padding()
            }
        }
        .navigationTitle("首页")
        .background(Color.gray.opacity(0.1).frame(height: 600).padding(.bottom))
    }
}

struct ImageCarouselView: View {
    @State private var selectedIndex: Int = 0
    let timer = Timer.publish(every: 2, on: .main, in: .common).autoconnect()
    
    var body: some View {
        TabView(selection: $selectedIndex) {
            ForEach(0..<5) { index in
                Image("image\(index + 1)")
                    .resizable()
                    .cornerRadius(10)
                    .tag(index)
            }
        }
        .tabViewStyle(PageTabViewStyle())
        .frame(height: 200)
        .onReceive(timer) { _ in
            withAnimation {
                let nextIndex = (selectedIndex + 1) % 5
                selectedIndex = nextIndex
            }
        }
    }
}



struct HotSpotView: View {
    @State private var isLearningPathViewPresented = false
    
    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text("热点指北")
                .font(.title)
                .fontWeight(.bold)
            
            HStack(spacing: 20) {
                HotSpotItemView(name: "入学准备")
                HotSpotItemView(name: "报到流程")
                HotSpotItemView(name: "学习路线")
                    .onTapGesture {
                        isLearningPathViewPresented = true
                    }
                
                HotSpotItemView(name: "宿舍介绍")
            }
        }
        .padding()
        .sheet(isPresented: $isLearningPathViewPresented) {
            LearningPathView()
        }
    }
}

struct HotForumTotalView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text("热点论坛")
                .font(.title)
                .fontWeight(.bold)
            
            VStack(spacing: 20) {
                HotForumTopicView(name: "东大学习论坛", intro: "这里是东北大学学习交流论坛，欢迎大家进入论坛畅所欲言")
                HotForumTopicView(name: "东大萌宠论坛", intro: "这里是东北大学萌宠论坛，欢迎大家进入论坛畅所欲言")
                HotForumTopicView(name: "东大日常论坛", intro: "这里是东北大学日常论坛，欢迎大家进入论坛畅所欲言")
            }
        }
        .padding()
    }
}

struct HotSpotItemView: View {
    let name: String
    
    var body: some View {
        VStack {
            Image(systemName: "location.north.fill")
                .foregroundColor(.blue)
                .frame(width: 55, height: 50)
            
            Text("\(name)")
                .fontWeight(.bold)
                .font(.system(size: 13))
        }
        .padding()
    }
}

struct HotForumTopicView: View {
    let name: String
    let intro:String
    
    var body: some View {
        HStack {
            Image(systemName: "flame.fill")
                .foregroundColor(.red)
                .padding(.trailing, 5)
            
            Text("\(name)")
                .font(.subheadline)
            
            Text("\(intro)")
                .font(.caption)
                .foregroundColor(.gray)
        }
        .padding()
    }
}
/*#########################################################*/

/*##################   指北界面    #########################*/
struct CampusGuideView: View {
    @State private var selectedCampusIndex: Int = 0
    @State private var selectedCollegeIndex: Int = 0
    @State private var selectedCampus: String = "选择校区"
    @State private var selectedCollege: String = "选择学院"
    @State private var isLearningPathViewPresented: Bool = false
    
    let campuses = ["浑南校区", "南湖校区"]
    let collegesForHunnan = ["软件学院", "计算机学院", "工商管理学院", "文法学院"]
    let collegesForNanhu = ["艺术学院", "自动化学院", "冶金学院"]
    
    let guidePostsForSoftware: [[String: String]] = [
        ["title": "入学准备", "content": "开开心心开学", "author": "Louis", "avatar": "avatar1"],
        ["title": "报到流程", "content": "如何优雅的完成报到", "author": "Lisa", "avatar": "avatar2"],
        ["title": "学习路线", "content": "东北大学软件学院2022级介绍以及推荐", "author": "Liu", "avatar": "avatar3"],
        ["title": "宿舍介绍", "content": "各个宿舍楼的介绍", "author": "Leo", "avatar": "avatar4"],
        ["title":"校园小动物指北", "content": "学校里有各种各样的小动物，一起来了解他们吧！", "author": "Sam", "avatar": "avatar5"],
        ["title": "校区布局", "content": "校区的缩略图如下", "author": "Sunny", "avatar": "avatar6"],
        ["title": "学校各个公共区域介绍", "content": "有如下公共区域", "author": "Rainy", "avatar": "avatar7"],
    ]
    
    let guidePostsForOther: [[String: String]] = [
        ["title": "入学准备", "content": "开开心心开学", "author": "Louis", "avatar": "avatar1"],
    ]
    
    var guidePosts: [[String: String]] {
        let selectedCollege = getColleges()[selectedCollegeIndex]
        switch selectedCollege {
        case "软件学院":
            return guidePostsForSoftware
        default:
            return guidePostsForOther
        }
    }
    
    var body: some View {
        NavigationView {
            VStack(spacing: 0) {
                HStack {
                    Picker(selectedCampus, selection: $selectedCampusIndex) {
                        ForEach(0..<campuses.count) { index in
                            Text(campuses[index]).tag(index)
                        }
                    }
                    .pickerStyle(MenuPickerStyle())
                    .padding(.top)
                    .onChange(of: selectedCampusIndex) { newValue in
                        updateSelectedCampus()
                    }
                    
                    Picker(selectedCollege, selection: $selectedCollegeIndex) {
                        ForEach(getColleges(), id: \.self) { college in
                            Text(college).tag(college)
                        }
                    }
                    .pickerStyle(MenuPickerStyle())
                    .padding(.top)
                    .onChange(of: selectedCollegeIndex) { newValue in
                        updateSelectedCollege()
                    }
                }
                
                Spacer()
                    .frame(height:4)
                
                List {
                    ForEach(guidePosts, id: \.self["title"]) { post in
                        HStack(alignment: .top, spacing: 10) {
                            LazyVStack(alignment: .leading, spacing: 5) {
                                Text(post["title"] ?? "")
                                    .font(.headline)
                                Text(post["content"] ?? "")
                                    .font(.caption)
                                    .lineLimit(3)
                                    .foregroundColor(.gray)
                                    .lineSpacing(4)
                            }
                            
                            Spacer()
                            
                            LazyVStack(alignment: .trailing, spacing: 5) {
                                Image(systemName: post["avatar"] ?? "person.circle.fill")
                                    .resizable()
                                    .frame(width: 40, height: 40)
                                    .clipShape(Circle())
                                Text(post["author"] ?? "")
                                    .font(.caption)
                                    .foregroundColor(.gray)
                            }
                        }
                        .padding()
                        .background(RoundedRectangle(cornerRadius: 8).fill(Color.gray.opacity(0.1)))
                        .onTapGesture {
                            if post["title"] == "学习路线" {
                                isLearningPathViewPresented = true
                            }
                        }
                    }
                }
            }
            .navigationBarHidden(true)
            .background(Color.white)
            .padding()
            .sheet(isPresented: $isLearningPathViewPresented) {
                LearningPathView()
            }
        }
    }
    
    func getColleges() -> [String] {
        return selectedCampusIndex == 0 ? collegesForHunnan : collegesForNanhu
    }
    
    func updateSelectedCampus() {
        selectedCampus = campuses[selectedCampusIndex]
        selectedCollege = getColleges()[0]
        selectedCollegeIndex = 0
    }
    
    func updateSelectedCollege() {
        selectedCollege = getColleges()[selectedCollegeIndex]
    }
}

struct LearningPathView: View {
    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 20) {
                Text("学习路线指北")
                    .font(.largeTitle)
                    .padding(.top)
                    .multilineTextAlignment(.trailing)

                Text("作者：Louis")
                                    .font(.subheadline)
                                    .foregroundColor(.gray)
                                    .padding(.bottom)
                                    .multilineTextAlignment(.center)
                
                Divider()
                    .background(Color.gray.opacity(0.1))
                   .padding(.horizontal)
                
                // 学习心得
                Text("""
                    学习软件工程是一次全面的体验，需要不断地更新自己的知识和技能。在这里，我学到了如何进行系统设计，编写高效的代码，以及如何与团队成员合作解决问题。

                    系统设计是软件工程的核心，它需要我们对问题有深入的理解，并找到最优的解决方案。编写高效的代码不仅可以提高程序的运行效率，还可以使代码更加易于维护和扩展。

                    与团队合作是软件开发中不可或缺的一部分，团队协作不仅可以加速项目的进展，还可以从不同的角度提出解决问题的方法。

                    总的来说，学习软件工程是一个持续学习和成长的过程，需要我们不断地积累经验，提高自己的技能。
                    """)
                    .padding([.leading, .bottom])
                    .padding(.horizontal, 16) // 设置左右边距
                    .lineSpacing(5) // 行间距
                    .fixedSize(horizontal: false, vertical: true) // 允许文本多行
                    .padding()
                
                VStack {
                    FlowStep(text: "Learn C")
                    ConnectorlTor()
                    FlowStep(text: "Learn Java")
                        .offset(x: 50)
                    ConnectorrTol()
                    FlowStep(text: "Learn Algorithm")
                    ConnectorlTor()
                    FlowStep(text: "Learn Python")
                        .offset(x: 50)
                    ConnectorrTol()
                    FlowStep(text: "Learn MySQL")
                }
            }
            .padding()
        }
    }
}

struct FlowStep: View {
    var text: String
    
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 25)
                .stroke(Color.green, lineWidth: 2)
                .frame(width: 100, height: 50)
            
            Text(text)
                .font(.caption)
                .foregroundColor(.black)
                .multilineTextAlignment(.center)
        }
    }
}


struct ConnectorlTor: View {
    var body: some View {
        Path { path in
            path.move(to: CGPoint(x: 200, y: -9))
            path.addQuadCurve(to: CGPoint(x: 250, y: 19), control: CGPoint(x: 225, y: 11))
        }
        .stroke(Color.green, lineWidth: 2)
    }
}

struct ConnectorrTol: View {
    var body: some View {
        Path { path in
            path.move(to: CGPoint(x: 250, y: -9))
            path.addQuadCurve(to: CGPoint(x: 200, y: 19), control: CGPoint(x: 225, y: 1))
        }
        .stroke(Color.green, lineWidth: 2)
    }
}
/*#########################################################*/

/*#################   论坛页面    ############################*/
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

    struct GPTResponse: Codable {
        let id: String
        let object: String
        let created: Int
        let model: String
        let choices: [GPTChoice]
        let usage: Usage
        let system_fingerprint: String
    }

    struct GPTChoice: Codable {
        let index: Int
        let message: Message
        let logprobs: Logprobs?
        let finish_reason: String
    }

    struct Message: Codable {
        let role: String
        let content: String
    }

    struct Logprobs: Codable {
        // 根据API的实际返回定义
    }

    struct Reply: Codable {
        var text: String
    }

    struct Usage: Codable {
        let prompt_tokens: Int
        let completion_tokens: Int
        let total_tokens: Int
    }

struct ForumView: View {
    @State private var showAllForums = false
    @State private var showChatWindow = false
    @State private var currentForumIndex: Int = 0
    @State private var inputText: String = ""
    @State private var recentPosts: [String] = [
        "大家最近学啥呢？",
        "前端呀！",
        "学SwiftUI呀，ios课上的展示app做的我头大。。。"
    ]

    let forums: [String] = [
        "学习交流论坛",
        "东大日常论坛",
        "东北大学萌宠论坛"
    ]
    
    @State private var chatText: String = ""
    @State private var aiResponse: String = ""
    
    
    var body: some View {
        VStack {
            // 标题和论坛名称横条
            VStack(alignment: .leading) {
                Text("论坛")
                    .font(.largeTitle)
                    .padding(.top)
                
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(spacing: 10) {
                        ForEach(0..<forums.count, id: \.self) { index in
                            Button(action: {
                                currentForumIndex = index
                                recentPosts = getPostsForForum(forum: forums[index])
                            }) {
                                Text(forums[index])
                                    .padding()
                                    .background(RoundedRectangle(cornerRadius: 16).fill(Color.white)) // 圆角边框
                                    .shadow(color: Color.black.opacity(0.2), radius: 5, x: 0, y: 5) // 投影效果
                            }
                        }
                    }
                    .frame(width: UIScreen.main.bounds.width * 1.2)
                    .padding(.top)
                }
            }
            .padding()
            .background(RoundedRectangle(cornerRadius: 20).fill(Color.white)) // 更大的圆角边框
            .shadow(color: Color.black.opacity(0.1), radius: 10, x: 0, y: 10) // 大的投影效果
            .padding()
            
            // 最近的论坛发言
            List(recentPosts, id: \.self) { post in
                Text(post)
            }
            
            // AI聊天按钮
            ZStack {
                Circle()
                    .foregroundColor(.blue)
                    .frame(width: 60, height: 60)
                    .offset(x: UIScreen.main.bounds.width / 3, y: -100)
                
                Button(action: {
                    showChatWindow.toggle()
                }) {
                    Image(systemName: "person.circle")
                        .resizable()
                        .frame(width: 60, height: 60)
                        .foregroundColor(.white)
                }
                .offset(x: UIScreen.main.bounds.width / 3, y: -100)
                .background(Color.clear)
            }
            
            
            // 输入框和发布按钮
            HStack {
                TextField("输入内容", text: $inputText)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding()
                
                Button(action: {
                    recentPosts.append(inputText)
                    inputText = ""
                }) {
                    Text("确定")
                        .padding()
                        .background(Color.blue)
                        .foregroundColor(.white)
                        .cornerRadius(8)
                }
                .padding()
            }
            
            
        }
        .background(Color.gray.opacity(0.1).frame(height:645))
        .sheet(isPresented: $showChatWindow) {
            ChatWithAIView(aiResponse: $aiResponse, chatText: $chatText)
        }
    }
    
    func getPostsForForum(forum: String) -> [String] {
            // Simulated posts for demonstration
            switch forum {
            case "学习交流论坛":
                return [
                    "关于SwiftUI有什么好的学习资源推荐吗？",
                    "最近在学习算法，有没有大神能推荐一些入门资源？"
                ]
            case "东大日常论坛":
                return [
                    "大家有没有什么好玩的活动推荐？",
                    "东大的图书馆最近有什么新书上架了吗？"
                ]
            case "东北大学萌宠论坛":
                return [
                    "最近领养了一只猫，大家有没有猫咪护理的建议？",
                    "东北大学附近有什么宠物店吗？"
                ]
            default:
                return []
            }
        }
}

struct ChatMessage: Identifiable {
    let id = UUID()
    let text: String
    let isUser: Bool // 用于区分是用户的问题还是GPT的回答
}

struct ChatWithAIView: View {
    @Binding var aiResponse: String
    @Binding var chatText: String
    @State private var chatMessages: [ChatMessage] = []
    @State private var cancellables: Set<AnyCancellable> = []

    var body: some View {
        VStack{
            Text("与AI对话")
                .font(.title)
                .padding(.top)
            
            Divider()
                .background(Color.gray)
                .padding(.horizontal)

            ScrollView {
                VStack(alignment: .leading, spacing: 10) {
                    ForEach(chatMessages) { message in
                        if message.isUser {
                            HStack {
                                Spacer()
                                Text(message.text)
                                    .padding()
                                    .background(Color.blue)
                                    .foregroundColor(.white)
                                    .cornerRadius(8)
                            }
                        } else {
                            HStack {
                                Text(message.text)
                                    .padding()
                                    .background(Color.gray.opacity(0.1))
                                    .foregroundColor(.black)
                                    .cornerRadius(8)
                                Spacer()
                            }
                        }
                    }
                }
                .padding(.top, 10)
                .padding(.horizontal)
            }
            HStack {
                TextField("输入问题", text: $chatText)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding(.leading, 3)

                Button(action: {
                    callBackendAPI(prompt: chatText) { response in
                                            DispatchQueue.main.async {
                                                aiResponse = response
                                            }
                                        }
//                    callGPTAPI(prompt: chatText, completion: { response in
//                        DispatchQueue.main.async {
//                            chatMessages.append(ChatMessage(text: chatText, isUser: true))
//                            chatMessages.append(ChatMessage(text: response, isUser: false))
//                            chatText = ""
//                        }
//                    }, onFailure: {
//                        DispatchQueue.main.async {
//                            chatMessages.append(ChatMessage(text: "请求失败，请稍后再试", isUser: false))
//                        }
//                    })
                }) {
                    Text("发送")
                        .padding()
                        .background(Color.blue)
                        .foregroundColor(.white)
                        .cornerRadius(8)
                }
            }
            .padding(.bottom)
        }
        .background(Color.white)
        .cornerRadius(20)
    }

    func callGPTAPI(prompt: String, completion: @escaping (String) -> Void, onFailure: @escaping () -> Void) {
        let apiKey = "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"
        let urlString = "https://gateway.ai.cloudflare.com/v1/3819b52e3ae6c46343a9f2e3d634036d/neu-cl/openai/chat/completions"
        
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            onFailure()
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        
        let requestData: [String: Any] = [
            "model": "gpt-3.5-turbo",
            "messages": [
                [
                    "role": "user",
                    "content": prompt
                ]
            ]
        ]
        
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: requestData, options: .prettyPrinted)
        } catch let error {
            print("Error serializing data: \(error.localizedDescription)")
            onFailure()
            return
        }
        
        URLSession.shared.dataTaskPublisher(for: request)
            .receive(on: DispatchQueue.main)
            .tryMap { data, response -> Data in
                guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
                    throw URLError(.badServerResponse)
                }
                return data
            }
            .decode(type: GPTResponse.self, decoder: JSONDecoder())
            .sink(receiveCompletion: { completion in
                switch completion {
                case .failure(let error):
                    print("Error: \(error)")
                    onFailure()
                case .finished:
                    break
                }
            }, receiveValue: { response in
                DispatchQueue.main.async {
                    completion(response.choices[0].message.content.trimmingCharacters(in: .whitespacesAndNewlines))
                }
            })
            .store(in: &cancellables)
    }
    
    func callBackendAPI(prompt: String, completion: @escaping (String) -> Void) {
            guard let url = URL(string: "http://localhost:8080/ask") else {
                print("Invalid URL")
                return
            }

            let requestData: [String: Any] = [
                "text": prompt
            ]

            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")

            do {
                request.httpBody = try JSONSerialization.data(withJSONObject: requestData, options: .prettyPrinted)
            } catch {
                print("Error serializing data: \(error)")
                return
            }

            URLSession.shared.dataTask(with: request) { data, response, error in
                guard let data = data else {
                    print("No data received: \(error?.localizedDescription ?? "Unknown error")")
                    return
                }

                do {
                    let decodedResponse = try JSONDecoder().decode(Reply.self, from: data)
                    completion(decodedResponse.text)
                } catch {
                    print("Error decoding response: \(error)")
                }
            }.resume()
        }
}


/*######################################################*/

/*##################     个人主页      ###################*/
struct ProfileView: View {
    let id: String // 用户ID
    let avatar: Image // 用户头像
    let myGuide: String // 我的指北
    let myPosts: String // 我的帖子
    let contactUs: String // 联系我们
    let version: String // 版本信息
    
    @State private var loggedInUser: String? = nil
    @State private var showingImagePicker = false
    @State private var selectedImage: Image? = nil
    @State private var showMyGuide = false
    @State private var showLogin = false
    
    var body: some View {
        VStack {
            ZStack {
                Color.gray
                
                // 显示选择的图片
                if let image = selectedImage {
                    image
                        .resizable()
                }
                else {
                    Text("Please select a background image!")
                }
                
                // 添加上传图片按钮
                Button(action: {
                    showingImagePicker = true
                }) {
                    Text("")
                        .foregroundColor(.white)
                        .padding()
                        .cornerRadius(8)
                }
                .sheet(isPresented: $showingImagePicker, onDismiss: loadImage) {
                    ImagePicker(image: $selectedImage)
                }
            }
            .frame(height: 250)
            .padding(.top, 17)
            
            Button(action: {
                if loggedInUser == nil {
                    showLogin = true
                }
            }) {
                HStack {
                    Text("ID: \(id)") // 显示ID
                        .font(.headline)
                    Spacer()
                    avatar // 显示头像
                        .resizable()
                        .frame(width: 50, height: 50)
                        .clipShape(Circle())
                }
            }
            .padding(.top, 20)
            .padding(.horizontal)
            .sheet(isPresented: $showLogin) {
                LoginView(onLogin: { email in
                    self.loggedInUser = email
                })

            }
            
            Divider()
                .background(Color.gray.opacity(0.7))
                .padding(.horizontal)
            
            Button(action: {
                showMyGuide = true
            }) {
                HStack {
                    Text("我的指北")
                        .font(.headline)
                    Spacer()
                    Image(systemName: "arrow.right")
                }
                .padding()
            }
            .sheet(isPresented: $showMyGuide) {
                MyGuideView()
            }
            
            HStack {
                Text("联系我们")
                    .font(.headline)
                Spacer()
                Text("muyenanhai123@gmail.com")
            }
            .padding()
            
            
            Spacer()
            
            HStack {
                Text("版本信息")
                    .font(.headline)
                
                Text(version)
            }
            .padding()
            .offset(y: -100)
            
        }
        .padding(.top)
        .ignoresSafeArea(.all)
    }
    
    func loadImage() {
        // 可以在这里实现图片加载逻辑，例如上传到服务器或保存到本地
    }
}

struct ImagePicker: UIViewControllerRepresentable {
    @Binding var image: Image?
    @Environment(\.presentationMode) private var presentationMode

    func makeUIViewController(context: Context) -> some UIViewController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        return picker
    }

    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        var parent: ImagePicker

        init(_ parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            if let uiImage = info[.originalImage] as? UIImage {
                parent.image = Image(uiImage: uiImage)
            }
            parent.presentationMode.wrappedValue.dismiss()
        }
    }
}

struct MyGuideView: View {
    @State private var showCreatePost = false
    @State private var guidePostsForMine: [[String: String]] = [
        ["title": "学习路线", "content": "东北大学软件学院2022级介绍以及推荐", "author": "Liu", "avatar": "avatar1"]
    ]
    var body: some View {
        VStack(spacing: 20) {
            Text("我的指北")
                .font(.largeTitle)
                .fontWeight(.bold)
            
            
                        
            List {
                ForEach(guidePostsForMine, id: \.self["title"]) { post in
                    HStack(alignment: .top, spacing: 10) {
                        VStack(alignment: .leading, spacing: 5) {
                            Text(post["title"] ?? "")
                                .font(.headline)
                            Text(post["content"] ?? "")
                                .font(.caption)
                                .lineLimit(3)
                                .foregroundColor(.gray)
                                .lineSpacing(4)
                        }
                        
                        Spacer()
                        
                        VStack(alignment: .trailing, spacing: 5) {
                            Image(systemName: post["avatar"] ?? "person.circle.fill")
                                .resizable()
                                .frame(width: 40, height: 40)
                                .clipShape(Circle())
                            Text(post["author"] ?? "")
                                .font(.caption)
                                .foregroundColor(.gray)
                        }
                    }
                    .padding()
                    .background(RoundedRectangle(cornerRadius: 8).fill(Color.gray.opacity(0.1)))
                   
                    Spacer()
                }
            }
            
            // 添加创建帖子的按钮
            VStack {
                Spacer()
                HStack {
                    Spacer()
                    Button(action: {
                        showCreatePost = true
                    }) {
                        Image(systemName: "plus.circle.fill")
                            .resizable()
                            .frame(width: 60, height: 60)
                            .foregroundColor(.green)
                    }
                    .padding()
                    .sheet(isPresented: $showCreatePost) {
                        CreatePostView(savePost: { title, content in
                            self.savePost(title: title, content: content)
                        })
                    }
                }
            }
        }
        .padding()
    }
    func savePost(title: String, content: String) {
        let newPost = ["title": title, "content": content, "author": "New Author", "avatar": "new_avatar"]
        guidePostsForMine.append(newPost)
    }
}

struct LoginView: View {
    @State private var email: String = ""
    @State private var password: String = ""
    @State private var showAlert = false
    @State private var alertMessage = ""
    var onLogin: (String) -> Void
    
    var body: some View {
        ZStack {
            Color.gray.opacity(0.1)
                .ignoresSafeArea()
            
            VStack(spacing: 20) {
                Spacer()
                Image(systemName: "person.circle.fill")
                    .resizable()
                    .foregroundColor(.blue)
                    .frame(width: 100, height: 100)
                
                Text("登录")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                    .foregroundColor(.blue)
                
                TextField("邮箱", text: $email)
                    .padding()
                    .background(RoundedRectangle(cornerRadius: 10).fill(Color.white))
                    .textFieldStyle(PlainTextFieldStyle())
                    .autocapitalization(.none)
                
                SecureField("密码", text: $password)
                    .padding()
                    .background(RoundedRectangle(cornerRadius: 10).fill(Color.white))
                    .textFieldStyle(PlainTextFieldStyle())
                
                HStack(spacing: 20) {
                    Button(action: {
                        print("尝试登录：\(email), \(password)")
                        login(email: email, password: password)
                    }) {
                        Text("确定")
                            .padding()
                            .foregroundColor(.white)
                            .background(Color.blue)
                            .cornerRadius(10)
                    }
                    
                    Button(action: {
                        showAlert = true // 点击取消按钮时显示警告框
                    }) {
                        Text("取消")
                            .padding()
                            .foregroundColor(.white)
                            .background(Color.gray)
                            .cornerRadius(10)
                    }
                }
                
                Spacer()
            }
            .padding()
        }
    }
    
    func login(email: String, password: String) {
        let sqlManager = SQLManager.shareInstance()
        sqlManager.createDataBaseTableIfNeeded()
        
        let querySQL = "SELECT * FROM users WHERE email = '\(email)' AND password = '\(password)';"
        if let result = sqlManager.queryDataBase(querySQL: querySQL) {
            if result.isEmpty {
                // 登录失败
                print("登录失败")
                showAlert = true
                alertMessage = "登录失败"
            } else {
                // 登录成功
                print("登录成功")
                onLogin(email)
                showAlert = true
                alertMessage = "登录成功"
            }
        } else {
            // 查询失败
            print("查询失败")
            showAlert = true
            alertMessage = "查询失败"
        }
    }

}

struct CreatePostView: View {
    @State private var title: String = ""
    @State private var content: String = ""
    @State private var newStepText: String = "" // 新添加的步骤文本
    @State private var steps: [FlowStepData] = [
        FlowStepData(text: "Start", position: .left)
    ]
    
    var savePost: (String, String) -> Void
    
    var body: some View {
        ScrollView {
            Text("创建帖子")
                .font(.largeTitle)
                .fontWeight(.bold)
            
            // 标题输入框
            VStack(alignment: .leading, spacing: 8) {
                Text("标题")
                    .font(.headline)
                
                TextField("输入标题", text: $title)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
            }
            
            // 简介输入框
            VStack(alignment: .leading, spacing: 8) {
                Text("简介")
                    .font(.headline)
                
                TextEditor(text: $content)
                    .frame(height: 150)
                    .overlay(
                        RoundedRectangle(cornerRadius: 8)
                            .stroke(Color.gray.opacity(0.5), lineWidth: 1)
                    )
            }
            
            // 新步骤输入框
            VStack(alignment: .leading, spacing: 8) {
                Text("新步骤")
                    .font(.headline)
                
                TextField("输入新步骤", text: $newStepText)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
            }
            
            // FlowDiagram
            FlowDiagram(steps: steps, newStepText: newStepText, onAddStep: { position in
                self.addStep(position: position, text: newStepText)
                self.newStepText = "" // 清空输入框
            })
            
            Button(action: {
                savePost(title, content)
            }) {
                Text("保存")
                    .padding()
                    .background(Color.green)
                    .foregroundColor(.white)
                    .cornerRadius(8)
            }
            
            Spacer()
        }
        .padding()
    }
    
    // 添加步骤
    func addStep(position: FlowStepPosition, text: String) {
        steps.append(FlowStepData(text: text, position: position))
    }
}

struct FlowDiagram: View {
    var steps: [FlowStepData]
    var newStepText: String // 新添加的步骤文本
    var onAddStep: (FlowStepPosition) -> Void
    
    var body: some View {
        VStack {
            ForEach(0..<steps.count, id: \.self) { index in
                let step = steps[index]
                FlowStep(text: step.text)
                    .offset(x: step.position == .left ? 0 : 50)
                
                if index < steps.count - 1 {
                    if steps[index + 1].position == .left {
                        ConnectorrTol()
                    } else {
                        ConnectorlTor()
                    }
                }
            }
            
            // 绿色小加号
            Button(action: {
                let lastStepPosition = steps.last?.position ?? .right
                let newPosition: FlowStepPosition = lastStepPosition == .right ? .left : .right
                
                onAddStep(newPosition)
            }) {
                Image(systemName: "plus.circle.fill")
                    .resizable()
                    .frame(width: 40, height: 40)
                    .foregroundColor(.green)
                    .offset(y: 0)
            }
        }
    }
}

enum FlowStepPosition {
    case left
    case right
}

struct FlowStepData {
    var text: String
    var position: FlowStepPosition
}


/*###########################################################*/
